package com.aijk.commons.task;

import com.aijk.commons.mq.entity.MqTopicConst;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.aijk.base.entity.TaskContext;
import com.aijk.commons.mq.entity.MqTaskEventResult;
import com.aijk.commons.mq.utils.MqUtils;
import com.aijk.commons.utils.IpUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * <p> 调度中心 作业AOP拦截器 </p>
 * <p> 前置拦截实现发送任务开始状态 </p>
 * <p> 后置拦截实现发送任务执行结果状态 </p>
 */
@Aspect
@Component
public class TaskInterceptor {

    private final Logger logger = LoggerFactory.getLogger(TaskInterceptor.class);

    private SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor("sys.out");

    /**
     * AOP拦截器
     *
     * @param pjp
     * @return
     */
    @Around(value = "execution(@com.aijk.commons.task.Task * *(..))")
    public Object taskCallAop(ProceedingJoinPoint pjp) {
        logger.info("接收到任务调度[start]...开始");
        TaskContext context = (TaskContext) pjp.getArgs()[0];
        MqTaskEventResult taskEventResult = new MqTaskEventResult();
        taskEventResult.setTaskId(context.getTaskId());
        taskEventResult.setId(context.getId());
        taskEventResult.setStartTime(new Date());
        taskEventResult.setStatus(TaskContext.RUN_STATS);
        SendResult startSendResult = MqUtils.sendMessage(MqTopicConst.GROUP_TASK_EVENT, MqTopicConst.TOPIC_TASK, MqTopicConst.TAG_TASK_START, String.valueOf(System.currentTimeMillis()), taskEventResult);
        logger.info("mq send start task result {}", startSendResult);
        executor.execute(() -> {
            try {
                pjp.proceed();
            } catch (Throwable throwable) {
                logger.error("TaskLog id is [{}]", context.getId());
                logger.error("执行任务调度模块出错", throwable);
            } finally {
                taskEventResult.setEndTime(new Date());
                taskEventResult.setInvokeTime((int) (taskEventResult.getEndTime().getTime() - taskEventResult.getStartTime().getTime()));
                taskEventResult.setProvider(IpUtils.getRealIp());
                SendResult sendSendResult = MqUtils.sendMessage(MqTopicConst.GROUP_TASK_EVENT, MqTopicConst.TOPIC_TASK, MqTopicConst.TAG_TASK_END, String.valueOf(System.currentTimeMillis()), taskEventResult);
                logger.info("mq send end task result {}", sendSendResult);
                logger.info("接收到任务调度[start]...结束");
            }
        });
        taskEventResult.setStatus(TaskContext.SUCCESS_STATS);

        return null;
    }
}
